import paho.mqtt.client as mqtt


# 方法2: 配置文件形式: 用户认证 + ssl/tls加密
Config = {
    "mqtt_broker": {
        "ip": "192.168.111.17",
        "port": 1883,
        "username": "test",
        "password": "test",
        "ca_file": "",
    },
}


class MqttClientTest:
    def __init__(self, config):
        self.config = config["mqtt_broker"]
        ip = config["mqtt_broker"]["ip"]
        port = config["mqtt_broker"]["port"]
        # 创建mqtt客户端
        client = mqtt.Client()
        client.on_connect = self.on_connect
        client.on_message = self.on_message  # 注册回调函数

        # 用户认证
        username = config["mqtt_broker"]["username"]
        password = config["mqtt_broker"]["password"]
        if username and password:
            client.username_pw_set(username, username)

        # ssl/tls认证
        ca_file = config["mqtt_broker"]["ca_file"]
        if ca_file:
            client.tls_set(ca_certs=ca_file)

        # 连接mqtt服务器
        client.connect(ip, port, 60)
        self.mqttc = client

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code " + str(rc))

    def on_message(self, client, userdata, msg):
        print("message received: " + msg.topic + " " + str(msg.payload))


if __name__ == "__main__":
    mqttimpl = MqttClientTest(Config)
    mqttimpl.mqttc.subscribe("test/aaa", qos=0)  # 订阅主题
    mqttimpl.mqttc.loop_forever()  # 保持连接
